package com.ysd.lis.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.WkKnowledge;
import com.ysd.lis.entity.WkKnowledgeCatalog;
import com.ysd.lis.entity.WkKnowledgeContent;
import com.ysd.lis.mapper.WkKnowledgeMapper;
import com.ysd.lis.request.KnowledgeDto;
import com.ysd.lis.request.KnowledgePageParam;
import com.ysd.lis.service.WkKnowledgeService;
import com.ysd.lis.util.ListToTreeUtil;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2024-03-12
 */
@Service
@Slf4j
public class WkKnowledgeServiceImpl extends ServiceImpl<WkKnowledgeMapper, WkKnowledge> implements WkKnowledgeService {
    @Autowired
    WkKnowledgeMapper wkKnowledgeMapper;

    @Override
    public Result findKnowledgePageList(KnowledgePageParam pageParam) {
        Page<WkKnowledge> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        LambdaQueryWrapper<WkKnowledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WkKnowledge::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(WkKnowledge::getName, pageParam.getSeachValue())
                    .or().like(WkKnowledge::getCode, pageParam.getSeachValue()));
        }

        if (ToolsUtils.isNotEmpty(pageParam.getStatus())) {
            lambdaQueryWrapper.eq(WkKnowledge::getStatus, pageParam.getStatus());
        }
        lambdaQueryWrapper.orderByAsc(WkKnowledge::getSeq);
        Page<WkKnowledge> knowledgePage = wkKnowledgeMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", knowledgePage);
    }

    /**
     * 不分页查询
     *
     * @return
     */
    @Override
    public Result findKnowledgeList() {
        LambdaQueryWrapper<WkKnowledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WkKnowledge::getDelFlag, 0)
                .eq(WkKnowledge::getStatus, 1)
                .orderByAsc(WkKnowledge::getSeq);
        List<WkKnowledge> wkKnowledges = wkKnowledgeMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", wkKnowledges);
    }

    @Override
    public Result getKnowledgeTree() {
        List<WkKnowledgeCatalog> knowledgeCatalogs = buildKnowledgeTree();
        JSONArray objects = ListToTreeUtil.forObjectAndLevelToTree(knowledgeCatalogs, "0", "id", "pid", "children", 1);
        return Result.succ(1, "查询成功！", objects);
    }

    @Override
    public Result batchDeleteKnowledgeList(KnowledgeDto dto) {
        List<WkKnowledge> knowledgeList = dto.getKnowledgeList();
        List<String> ids = knowledgeList.stream().map(WkKnowledge::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result addKnowledge(WkKnowledge knowledge) {
        int insert = wkKnowledgeMapper.insert(knowledge);
        if (insert > 0) {
            return Result.succ(1, "添加成功", knowledge);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result editKnowledge(WkKnowledge knowledge) {
        int updateById = wkKnowledgeMapper.updateById(knowledge);
        if (updateById > 0) {
            return Result.succ(1, "提交成功", knowledge);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result uploadKnowledgeImg(String id, String path) {
        LambdaUpdateWrapper<WkKnowledge> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(WkKnowledge::getImage, path)
                .set(WkKnowledge::getImageName, FileUtil.getName(path))
                .eq(WkKnowledge::getId, id);
        int update = wkKnowledgeMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            return Result.succ(1, "上传图片成功", update);
        } else {
            return Result.fail("上传图片失败！");
        }
    }

    public List<WkKnowledgeCatalog> buildKnowledgeTree() {
        MPJLambdaWrapper<WkKnowledge> lambdaWrapper = JoinWrappers.lambda(WkKnowledge.class)
                .selectAll(WkKnowledge.class)
                .selectCollection(WkKnowledgeCatalog.class, WkKnowledge::getWkKnowledgeCatalogList, b -> b
                        .collection(WkKnowledgeContent.class, WkKnowledgeCatalog::getWkKnowledgeContentList))
                .leftJoin(WkKnowledgeCatalog.class, on -> on.eq(WkKnowledgeCatalog::getKnowledgeId, WkKnowledge::getId).eq(WkKnowledgeCatalog::getDelFlag, 0))
                .leftJoin(WkKnowledgeContent.class, on -> on.eq(WkKnowledgeContent::getCatalogId, WkKnowledgeCatalog::getId).eq(WkKnowledgeContent::getDelFlag, 0).ge(WkKnowledgeContent::getStatus, 10))
                .eq(WkKnowledge::getDelFlag, 0);
        List<WkKnowledge> knowledgeList = wkKnowledgeMapper.selectJoinList(WkKnowledge.class, lambdaWrapper);
        List<WkKnowledgeCatalog> wkKnowledgeCatalogs = new ArrayList<>();
        knowledgeList.stream().forEach(knowledge -> {
            List<WkKnowledgeCatalog> collect = knowledge.getWkKnowledgeCatalogList().stream().map(item -> {
                item.setKnType("catalog");
                return item;
            }).flatMap(item -> item.getWkKnowledgeContentList().stream().map(content -> {
                WkKnowledgeCatalog wkKnowledgeCatalog = new WkKnowledgeCatalog();
                wkKnowledgeCatalog.setId(content.getId());
                wkKnowledgeCatalog.setPid(content.getCatalogId());
                wkKnowledgeCatalog.setName(content.getTitle());
                wkKnowledgeCatalog.setKnType("content");
                return wkKnowledgeCatalog;
            })).collect(Collectors.toList());
            wkKnowledgeCatalogs.addAll(collect);
            wkKnowledgeCatalogs.addAll(knowledge.getWkKnowledgeCatalogList().stream().map(item -> {
                item.setKnType("catalog");
                if ("0".equals(item.getPid())) {
                    item.setPid(item.getKnowledgeId());
                }
                return item;
            }).collect(Collectors.toList()));
            WkKnowledgeCatalog wkKnowledgeCatalog = new WkKnowledgeCatalog();
            wkKnowledgeCatalog.setId(knowledge.getId());
            wkKnowledgeCatalog.setKnowledgeId(knowledge.getId());
            wkKnowledgeCatalog.setName(knowledge.getName());
            wkKnowledgeCatalog.setPid("0");
            wkKnowledgeCatalog.setKnType("catalog");
            wkKnowledgeCatalogs.add(wkKnowledgeCatalog);
        });
        return wkKnowledgeCatalogs;
    }
}
